<template>
  <div class="index-container">
    <p>剩余时间：{{ formattedTime }}</p>
    <button @click="startCountdown" class="start">开始倒计时</button>
    <button @click="stopCountdown" class="stop">停止倒计时</button>
  </div>
</template>



<script setup lang='ts'>
defineOptions({
  name:'sr-countdown'
})
import { ref, computed } from 'vue';



let time = ref(90); 
let countdownActive = ref(false);


let formattedTime = computed(() => {
  let minutes = Math.floor(time.value / 60);
  let seconds = time.value % 60;//将时间转换为分钟和秒
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
});

// 用于存储计时器的引用  有瑕疵
let timerInterval: any;

let startCountdown = () => {
  if (!countdownActive.value) {
    countdownActive.value = true; 
    timerInterval = setInterval(() => {
      if (time.value > 0) {
        time.value--; 
      } else {
        stopCountdown(); 
      }
    }, 1000);
  }
};

let stopCountdown = () => {
  countdownActive.value = false; 
  clearInterval(timerInterval); 
  time.value = 30; 
};

</script>

<style scoped lang="scss">
.index-container{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  font-size: 1.5rem;
  button{
    margin-top: 1.5rem,;
    padding: 1rem 1.5rem;
    font-size: 1rem;
    cursor: pointer;
  }
  .start{
    background-color: #4CAF50;
    color: white;
  }
  .stop{
    background-color: #f44336;
    color: white;
  }
}
</style>